package com.irdstudio.basic.sequence.service.impl;

import com.irdstudio.basic.sequence.service.exception.UidGenerateException;
import com.irdstudio.basic.sequence.service.facade.ClassableSeqService;
import com.irdstudio.basic.sequence.service.impl.support.segment.IDGen;
import com.irdstudio.basic.sequence.service.impl.support.segment.common.Result;
import com.irdstudio.basic.sequence.service.impl.support.segment.common.Status;

/**
 * @description:适配美团Leaf基于Segment号段的流水号生成策略，不同业务类型具备不同的序号空间
 * 				最大序列号为2的63次方，不具备自动重置功能，基本有序。
 * @date:2019年2月13日 下午5:34:18
 * @author:hengyh
 */
public class SegmentSeqAdapter implements ClassableSeqService {
    private IDGen idGen;

    public SegmentSeqAdapter(IDGen idGen) {
        this.idGen = idGen;
    }

    @Override
    public String getSequence(String key) {
        Result result = idGen.get(key);
        if (result.getStatus() == Status.EXCEPTION) {
            throw new UidGenerateException();
        } else {
            return String.valueOf(result.getId());
        }
    }
}
